﻿using System;
using System.Data;
using DataScripter.Database;
using DataScripter.Scripting;
using DataScripter.Scripting.Output;
using DataScripter.Scripting.Output.Sql.SqlServer;
using DataScripter.Scripting.OutputDestinations;
using DataScripter.Scripting.ScriptDefinitions;
using DataScripter.UnitTests.Factories;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace DataScripter.UnitTests.OutputProducerTests.Sql.SqlServer.Insert
{
    [TestClass]
    public class WhenReaderHasOneRecordAndTheTableHasOneGuidFieldWhichIsThePrimaryKey
    {
        private readonly MemoryScriptResult _scriptResult;

        public WhenReaderHasOneRecordAndTheTableHasOneGuidFieldWhichIsThePrimaryKey()
        {
            Engine engine = new Engine();
            IOutputDestination outputDestination = new FileOutputDestination("", engine);
            engine.RegisterType(outputDestination);

            InsertOutputProducer insertOutputProducer = new InsertOutputProducer(outputDestination);

            IScriptDefinition scriptDefinition = new ScriptDefinition("", engine);
            engine.RegisterType(scriptDefinition);

            _scriptResult = new MemoryScriptResult();
            insertOutputProducer.InitializeScript(engine, _scriptResult);

            ITableScriptRequest tableScriptRequest = scriptDefinition.InstallScriptRequest("abc");
            tableScriptRequest.UsedQuery = "myQuery";
            Mock<ITableStructure> tableStructureMock = tableScriptRequest.InstallTableStructure(new[] { FieldInfo.Guid("Abc_IAmAGuid") }, 0);
            IDataReader reader = tableStructureMock.ConstructReader(new[] { new object[] { new Guid("63f9c713-1322-4401-95b3-456691717329") } });
            insertOutputProducer.ProduceOutput(reader, tableScriptRequest);
            insertOutputProducer.FinalizeScript();
            _scriptResult.Close(); // performed by engine itself - don't use in engine client code
        }

        [TestMethod]
        public void ExpectedOutputShouldNotContainInsertStatements()
        {
            const string expected = @"SET XACT_ABORT ON
SET NOCOUNT ON
BEGIN TRANSACTION
/*
TABLE: abc
QUERY: myQuery
*/
--abc: Found 63f9c713-1322-4401-95b3-456691717329
INSERT INTO abc(Abc_IAmAGuid) VALUES ('63f9c713-1322-4401-95b3-456691717329')

COMMIT TRANSACTION
";
            Assert.AreEqual(expected, _scriptResult.Output);
        }
    }
}